package com.leetcodehot.problems;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class problems2415 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode reverseOddLevels(TreeNode root) {
        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.addLast(root);
        int level = 0;
        while (!deque.isEmpty()) {
            int n = deque.size();
            List<TreeNode> list = new ArrayList<>();
            while (n-- > 0) {
                TreeNode node = deque.removeFirst();
                if (level % 2 == 1) {
                    list.add(node);
                }
                if (node.left != null) {
                    deque.addLast(node.left);
                }
                if (node.right != null) {
                    deque.addLast(node.right);
                }
            }
            for (int i = 0; i < list.size() / 2; i++) {
                TreeNode p = list.get(i);
                TreeNode q = list.get(list.size() - i - 1);
                int temp = p.val;
                p.val = q.val;
                q.val = temp;
            }
            level++;
        }
        return root;
    }
}
